package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    
    @Autowired
    private CheckGroupDao checkGroupDao;
    
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.add(checkGroup);
        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);
    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> groupPage = checkGroupDao.findByQueryString(queryString);
        return new PageResult(groupPage.getTotal(),groupPage.getResult());
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    //编辑检查组
    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //删除依赖表中的信息
        checkGroupDao.deleteCheckGroupItemById(checkGroup.getId());
        //编辑检查组信息
        checkGroupDao.edit(checkGroup);
        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);
    }

    @Override
    public void delete(Integer id) {
        //先删除依赖关系
        checkGroupDao.deleteCheckGroupItemById(id);
        //删除检查组中的信息
        checkGroupDao.delete(id);
    }

    //查询检查组中的全部内容
    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }

    @Override
    public List<CheckGroup> findByCondition(String queryString) {
        return checkGroupDao.findByCondition(queryString);
    }

    public void setCheckGroupAndCheckItem(Integer checkgroupId, Integer[] checkitemIds) {
        if(checkitemIds != null && checkitemIds.length > 0) {
            for (Integer checkitemId : checkitemIds) {
                checkGroupDao.setCheckGroupAndCheckItem(checkgroupId,checkitemId);
            }
        }
    }
}
